// 菜单配置
export interface MenuItem {
  id: string
  title: string
  icon?: string
  path?: string
  children?: MenuItem[]
  hidden?: boolean
  roles?: string[]
  permissions?: string[]
}

export const menuConfig: MenuItem[] = [
  {
    id: 'dashboard',
    title: '仪表盘',
    icon: 'House',
    path: '/dashboard'
  },
  {
    id: 'users',
    title: '用户管理',
    icon: 'User',
    children: [
      {
        id: 'user-list',
        title: '用户列表',
        path: '/users/list',
        permissions: ['user:read']
      },
      {
        id: 'user-roles',
        title: '角色管理',
        path: '/users/roles',
        permissions: ['system:role']
      }
    ]
  },
  {
    id: 'settings',
    title: '系统设置',
    icon: 'Setting',
    path: '/settings',
    permissions: ['system:setting']
  }
]

// 根据权限过滤菜单
export function filterMenuByPermissions(
  menus: MenuItem[],
  userPermissions: string[] = [],
  userRoles: string[] = []
): MenuItem[] {
  return menus.filter(menu => {
    // 检查角色权限
    if (menu.roles && menu.roles.length > 0) {
      const hasRole = menu.roles.some(role => userRoles.includes(role))
      if (!hasRole) return false
    }

    // 检查具体权限
    if (menu.permissions && menu.permissions.length > 0) {
      const hasPermission = menu.permissions.some(permission => userPermissions.includes(permission))
      if (!hasPermission) return false
    }

    // 如果有子菜单，递归过滤
    if (menu.children && menu.children.length > 0) {
      menu.children = filterMenuByPermissions(menu.children, userPermissions, userRoles)
      // 如果过滤后没有子菜单，则隐藏父菜单
      if (menu.children.length === 0) return false
    }

    return !menu.hidden
  })
}

// 获取所有菜单路径（用于面包屑导航）
export function getAllMenuPaths(menus: MenuItem[]): Record<string, string[]> {
  const pathMap: Record<string, string[]> = {}

  function traverse(items: MenuItem[], parentTitles: string[] = []) {
    items.forEach(item => {
      if (item.path) {
        pathMap[item.path] = [...parentTitles, item.title]
      }

      if (item.children && item.children.length > 0) {
        traverse(item.children, [...parentTitles, item.title])
      }
    })
  }

  traverse(menus)
  return pathMap
}

// 根据路径查找菜单项
export function findMenuByPath(menus: MenuItem[], path: string): MenuItem | null {
  for (const menu of menus) {
    if (menu.path === path) {
      return menu
    }

    if (menu.children && menu.children.length > 0) {
      const found = findMenuByPath(menu.children, path)
      if (found) return found
    }
  }

  return null
}
